﻿using Books.Common;
using Books.Model;
using Books.SQLite;
using Books.View;
using Books.ViewModel;
using Services.Model;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace Books.Controls
{
    public sealed partial class ChapterControls : UserControl
    {
        private DownloadOperation activeDownload;
        DispatcherTimer times;
        private string fileNameDownload = string.Empty;
        private List<FileDownLoadComplete> filesDownload;
        private ChapterList data
        {
            get { return (ChapterList)DataContext; }
        }
        public ChapterControls()
        {
            this.InitializeComponent();

        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {


        }

        public async Task DownloadFile(string url, string chapter_id)
        {

            showProcess.Visibility = Windows.UI.Xaml.Visibility.Visible;
            var uri = new Uri(url);
            fileNameDownload = GetFileName(chapter_id, uri);
           
            var downloader = new BackgroundDownloader();
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileNameDownload,
                CreationCollisionOption.ReplaceExisting);
            DownloadOperation download = downloader.CreateDownload(uri, file);
            await StartDownloadAsync(download);
        }
        private async Task ResumeDownloadAsync(DownloadOperation downloadOperation)
        {

            activeDownload = downloadOperation;
            var progress = new Progress<DownloadOperation>(ProgressCallback);
            await downloadOperation.AttachAsync().AsTask(progress);
        }


        private async void ProgressCallback(DownloadOperation obj)
        {
            double progress = ((double)obj.Progress.BytesReceived / obj.Progress.TotalBytesToReceive);
            var getPercent = progress * 100;
            loadPercent.Text = getPercent.ToString("0.00", CultureInfo.CurrentUICulture);
            progressBar.Value = getPercent;
            if (progress >= 1.0)
            {
                //Set times deplay two seconds to save database complete
                times = new DispatcherTimer();
                times.Interval = TimeSpan.FromSeconds(2.0);
                times.Tick += times_Tick;
                times.Start();
            }
        }
        private async void ShowMedia(StorageFile files)
        {
            App.rootFrame = Window.Current.Content as Frame;
            var getPage = App.rootFrame.Content as DetailPage;
            getPage.AddControl(files);
        }
        async void times_Tick(object sender, object e)
        {
            data.IsDownload = true;
            showProcess.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            times.Stop();
            times.Tick -= times_Tick;
            activeDownload = null;
            var fileDownloaded = ManagerFilesDownloadComplete.SaveDataFilesDownloadComplete(new FileDownLoadComplete() { IsDownLoadComplete = true, FileName = fileNameDownload });
           
            var getDataFromLocal = await ApplicationData.Current.LocalFolder.GetFileAsync(fileNameDownload);
            ShowMedia(getDataFromLocal);


        }
        private async Task StartDownloadAsync(DownloadOperation downloadOperation)
        {
            //DownloadButton.IsEnabled = false;
            activeDownload = downloadOperation;
            var progress = new Progress<DownloadOperation>(ProgressCallback);
            await downloadOperation.StartAsync().AsTask(progress);
        }
        private string GetFileName(string bookId, Uri url)
        {
            string temp = string.Empty;
            var toStringUrl = url.LocalPath;
            if (toStringUrl.StartsWith("/resources/"))
                temp = toStringUrl.Replace("/resources/", string.Empty);
            temp = temp.Replace("/", "_");
            temp = string.Concat(bookId, temp);
            return temp;
        }

        private async void HandleDownloadFile(object sender, TappedRoutedEventArgs e)
        {
            if (data != null && data.isDownload)
            {

                showProcess.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                fileNameDownload = GetFileName(data.chapter_id, new Uri(data.audio_link));
                var getDataFromLocal = await ApplicationData.Current.LocalFolder.GetFileAsync(fileNameDownload);
                ShowMedia(getDataFromLocal);
            }
            else
            {
               
                var getLink = data.audio_link;
                if (getLink != string.Empty)
                    await DownloadFile(getLink, data.chapter_id);
            }
        }
    }
}

